<!-- 选取部门职务 -->
<template>
  <div>
    <el-dialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      :title="type == 1 ? '选取职务' : '选取部门'"
      :close-on-click-modal="false"
      top="50px"
      width="850px"
      @close="closeDialog"
    >
      <div class="search-box">
        <span class="selected-num">已选 {{ tableData.length }} 个</span>
        <span class="clear-btn" @click="clearTeacher">清空</span>
      </div>
      <div class="table-box" v-loading="loading">
        <div class="left-box">
          <!-- 全选 -->
          <el-checkbox
            v-model="allChecked"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <el-tree
            ref="treeDataRef"
            :data="treeData"
            show-checkbox
            node-key="id"
            highlight-current
            :default-checked-keys="defaultCheckedKeys"
            :props="defaultProps"
          />
        </div>
        <div class="center-box">
          <el-button type="primary" @click="handleCheckChange">
            <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
        <div class="left-box">
          <el-table :data="tableData">
            <el-table-column
              prop="caption"
              :label="type == 1 ? '职务' : '部门'"
            />
            <el-table-column header-align="center" width="35px">
              <template #default="{ $index }">
                <el-icon class="close-btn" @click="handleClose($index)">
                  <CircleCloseFilled />
                </el-icon>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="dialog-footer">
        <el-button
          type="primary"
          @click="handleSubmit"
          class="btn-submit"
          :disabled="loading"
        >
          保 存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElTree } from "element-plus";
import { ArrowRight, CircleCloseFilled } from "@element-plus/icons-vue";
import { departmentApi, positionApi } from "@/services/api/flow";
const emits = defineEmits(["closeDialog"]);
const treeDataRef = ref(ElTree);

let state = reactive({
  dialogVisible: false,
  treeData: [],
  tableData: [],
  loading: false,
  type: "1",
  defaultProps: {
    children: "teachers",
    label: "caption",
  },
  defaultCheckedKeys: [], //默认选中的节点
  allChecked: false,
  isIndeterminate: false,
});
let {
  dialogVisible,
  treeData,
  tableData,
  loading,
  defaultProps,
  defaultCheckedKeys,
  allChecked,
  isIndeterminate,
} = toRefs(state);

const props = defineProps({
  importVisible: {
    type: Boolean,
    require: true,
    default: false,
  },
  checkedList: {
    type: Array,
    default: () => [],
  },
  type: {
    type: Number,
    default: 1,
  },
});
function handleCheckAllChange() {
  if (state.allChecked) {
    treeDataRef.value.setCheckedNodes(state.treeData);
  } else {
    treeDataRef.value.setCheckedNodes([]);
  }
}
/**
 * 获取职务列表
 */
function getDepartmentList() {
  return new Promise((resolve, reject) => {
    state.loading = true;
    positionApi()
      .then((res) => {
        if (res.code == 1) {
          state.treeData = res.data;
        }
        state.loading = false;
        resolve(true);
      })
      .catch(() => {
        reject(false);
        state.loading = false;
      });
  });
}
/**
 * 获取部门列表
 */
function getDeptList() {
  return new Promise((resolve, reject) => {
    state.loading = true;
    departmentApi()
      .then((res) => {
        if (res.code == 1) {
          state.treeData = res.data;
        }
        state.loading = false;
        resolve(true);
      })
      .catch(() => {
        reject(false);
        state.loading = false;
      });
  });
}
/**
 * 选择教师
 */
function handleCheckChange() {
  const checkList = treeDataRef.value.getCheckedNodes();
  // 删除tableData中有但checkList中没有的项
  state.tableData = state.tableData.filter((item) =>
    checkList.find((obj) => obj.id === item.id),
  );
  // 添加checkList中有但tableData中没有的项
  checkList.forEach((item) => {
    if (!state.tableData.find((obj) => obj.id === item.id)) {
      state.tableData.push(item);
    }
  });
}
/**
 * 清空教师
 */
function clearTeacher() {
  state.tableData = [];
  treeDataRef.value.setCheckedKeys([]);
}
/**
 * 删除教师
 */
function handleClose(index) {
  let nodeKey = state.tableData[index].id;
  treeDataRef.value.setChecked(nodeKey, false);
  state.tableData.splice(index, 1);
}
/**
 * 保存
 */
function handleSubmit() {
  let checkedList = [];
  state.tableData.forEach((u) => {
    checkedList.push({
      id: u.id,
      name: u.caption,
      type: props.type == 1 ? 2 : 3, //职务2，部门3
      teach_count: u.teach_count,
    });
  });

  emits("closeDialog", checkedList);
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  emits("closeDialog", false);
}
/**
 * 监听父组件传过来的值
 */
async function handleOpenDialog() {
  state.dialogVisible = props.importVisible;
  if (props.importVisible) {
    if (props.type == 1) {
      await getDepartmentList();
    } else {
      await getDeptList();
    }
    state.defaultCheckedKeys = props.checkedList.map((item) => item.id);
    nextTick(() => {
      treeDataRef.value.setCheckedKeys(state.defaultCheckedKeys);
      state.tableData = [];
      handleCheckChange();
    });
    watch(
      () => treeDataRef.value.getCheckedNodes(),
      () => {
        let checkedNodes = treeDataRef.value.getCheckedNodes();
        if (checkedNodes.length == state.treeData.length) {
          state.allChecked = true;
          state.isIndeterminate = false;
        } else {
          if (checkedNodes.length > 0) {
            state.allChecked = false;
            state.isIndeterminate = true;
          } else {
            state.isIndeterminate = false;
            state.allChecked = false;
          }
        }
      },
    );
  }
}

watch(
  () => props.importVisible,
  () => {
    handleOpenDialog();
  },
);
</script>

<style lang="scss" scoped>
.search-box {
  margin-top: 10px;
  .selected-num {
    margin-left: 480px;
    vertical-align: bottom;
  }
  .clear-btn {
    margin-left: 220px;
    color: red;
    cursor: pointer;
    vertical-align: bottom;
  }
  .add-input {
    width: 200px;
    margin-right: 10px;
  }
}
.table-box {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  .left-box {
    width: 350px;
    height: 530px;
    padding: 5px;
    box-sizing: border-box;
    border-radius: 5px;
    border: 1px solid #c4c7cf;
    overflow-y: auto;
    .close-btn {
      margin-left: -9px;
      vertical-align: middle;
      font-size: 20px;
      color: #c4c7cf;
      cursor: pointer;
    }
  }
  .center-box {
    padding-top: 250px;
  }
}
.dialog-footer {
  margin-top: 25px;
  text-align: center;
  .btn-submit {
    width: 200px;
  }
}
:deep(.el-tree .el-icon) {
  color: #a8abb2;
}
</style>
